<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>检验数据录入</span>
          <div>
            <el-button icon="Back" @click="goBack" class="ml5">返回</el-button>
          </div>
        </div>
      </template>

      <el-row :gutter="20" v-loading="taskLoading">
        <el-col :span="24">
          <el-descriptions title="任务信息" :column="3" border>
            <el-descriptions-item label="任务编号">{{ taskInfo.taskCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="产品名称">{{ taskInfo.productName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="批次号">{{ taskInfo.batchCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="工序名称">{{ taskInfo.processName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="检验类型">{{ taskInfo.inspectionType || '-' }}</el-descriptions-item>
            <el-descriptions-item label="检验人员">{{ taskInfo.inspector || '-' }}</el-descriptions-item>
            <el-descriptions-item label="任务状态">
              <el-tag :type="taskInfo.taskStatus == 2 ? 'warning' : (taskInfo.taskStatus == 3 ? 'success' : 'info')">
                {{ getTaskStatusText(taskInfo.taskStatus) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <el-divider content-position="center">检验数据列表</el-divider>

      <!-- 导出工具栏 - 对所有状态可见 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Download"
            @click="handleExport"
            :disabled="dataList.length === 0"
            v-hasPermi="['qep:inspection:data:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Download"
            @click="handleExportSelected"
            :disabled="multiple"
            v-hasPermi="['qep:inspection:data:export']"
          >导出选中</el-button>
        </el-col>
      </el-row>

      <!-- 编辑工具栏 - 仅检验中状态可见 -->
      <el-row :gutter="10" class="mb8" v-if="taskInfo.taskStatus == 2">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['qep:inspection:data:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['qep:inspection:data:import']"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['qep:inspection:data:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Check"
            @click="handleFinishTask"
            v-hasPermi="['qep:inspection:task:finish']"
          >完成任务</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="expand">
          <template #default="scope">
            <el-form label-position="left" inline class="detail-form">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="参数ID">
                    <span>{{ scope.row.paramId }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="scope.row.isQualified === 0">
                  <el-form-item label="责任人">
                    <span>{{ scope.row.responsiblePerson || '-' }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="scope.row.isQualified === 0">
                  <el-form-item label="处理结果">
                    <span>{{ scope.row.processResult || '-' }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="scope.row.remark">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <span>{{ scope.row.remark }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="scope.row.defectImagePath">
                <el-col :span="24">
                  <el-form-item label="缺陷图片">
                    <el-image 
                      :src="scope.row.defectImagePath" 
                      :preview-src-list="[scope.row.defectImagePath]"
                      style="width: 120px; height: 120px"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="scope.row.attachmentUrl">
                <el-col :span="24">
                  <el-form-item label="附件">
                    <el-link :href="scope.row.attachmentUrl" target="_blank" type="primary">
                      查看附件
                    </el-link>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="参数名称" align="center" prop="paramName" min-width="120" />
        <el-table-column label="标准值" align="center" prop="standardValue" min-width="110" />
        <el-table-column label="实测值" align="center" prop="measuredValue" min-width="110" />
        <el-table-column label="是否合格" align="center" prop="isQualified" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isQualified === 1 ? 'success' : 'danger'">
              {{ scope.row.isQualified === 1 ? '合格' : '不合格' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="缺陷名称" align="center" prop="defectName" min-width="120" v-if="hasDefectData" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" v-if="taskInfo.taskStatus == 2">
          <template #default="scope">
            <el-button 
              link type="primary" 
              icon="Edit" 
              @click="handleUpdate(scope.row)"
              v-hasPermi="['qep:inspection:data:edit']"
            >修改</el-button>
            <el-button 
              link type="primary" 
              icon="Delete" 
              @click="handleDelete(scope.row)"
              v-hasPermi="['qep:inspection:data:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改检验数据对话框 -->
      <el-dialog :title="title" v-model="open" width="700px" append-to-body>
        <el-form ref="dataForm" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="参数名称" prop="paramName">
                <el-select v-model="form.paramName" placeholder="请选择参数名称" filterable @change="handleParameterChange">
                  <el-option
                    v-for="item in parameterOptions"
                    :key="item.id"
                    :label="item.paramName"
                    :value="item.paramName"
                    :data="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参数ID" prop="paramId">
                <el-input v-model="form.paramId" placeholder="系统自动填充" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="标准值" prop="standardValue">
                <el-input v-model="form.standardValue" placeholder="系统自动填充" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实测值" prop="measuredValue">
                <el-input v-model="form.measuredValue" placeholder="请输入实测值" @input="handleMeasuredValueChange" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否合格" prop="isQualified">
                <el-tag :type="form.isQualified === 1 ? 'success' : 'danger'">
                  {{ form.isQualified === 1 ? '合格' : '不合格' }}
                </el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.isQualified === 0">
              <el-form-item label="缺陷类型" prop="defectId">
                <el-select v-model="form.defectId" placeholder="请选择缺陷类型" filterable>
                  <el-option
                    v-for="item in defectOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.isQualified === 0">
            <el-col :span="12">
              <el-form-item label="责任人" prop="responsiblePerson">
                <el-input v-model="form.responsiblePerson" placeholder="请输入责任人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="处理结果" prop="processResult">
                <el-input v-model="form.processResult" placeholder="请输入处理结果" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 导入对话框 -->
      <el-dialog title="导入检验数据" v-model="importOpen" width="400px" append-to-body>
        <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?taskId=' + taskId + '&updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
              <el-link type="primary" :underline="false" style="font-size:12px;margin-left:8px" @click="importTemplate">下载模板</el-link>
            </div>
            <div class="el-upload__tip" style="color:red">提示：仅允许导入xls、xlsx格式文件！</div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="importOpen = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 完成检验任务对话框 -->
      <el-dialog title="完成检验任务" v-model="finishOpen" width="500px" append-to-body>
        <el-form ref="finishForm" :model="finishForm" :rules="finishRules" label-width="100px">
          <el-form-item label="实际日期" prop="actualDate">
            <el-date-picker
              v-model="finishForm.actualDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="检验结论" prop="inspectionResult">
            <el-select v-model="finishForm.inspectionResult" placeholder="请选择检验结论">
              <el-option label="合格" value="合格" />
              <el-option label="不合格" value="不合格" />
              <el-option label="特采" value="特采" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFinishForm">确 定</el-button>
            <el-button @click="cancelFinish">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { parseTime } from '@/utils/ruoyi';
import { download } from '@/utils/request';
import { getInspectionTask, finishInspectionTask } from '@/api/qep/inspection/task';
import { 
  listInspectionDataByTaskId, 
  addInspectionData, 
  updateInspectionData, 
  delInspectionData, 
  delInspectionDataByTaskId,
  importInspectionData,
  getImportTemplate,
  exportInspectionData,
  exportSelectedInspectionData,
  getParametersByTaskId
} from '@/api/qep/inspection/data';
import { listDefect } from '@/api/qep/inspection/defect';
import { getToken } from '@/utils/auth';

const route = useRoute();
const router = useRouter();
const taskId = ref(route.params.taskId);

// 任务信息
const taskInfo = ref({});
// 检验数据列表
const dataList = ref([]);
// 缺陷类型选项
const defectOptions = ref([]);
// 参数选项数组
const parameterOptions = ref([]);
// 当前选中的参数信息
const currentParameter = ref(null);
// 加载状态
const taskLoading = ref(false);
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非多个禁用
const multiple = computed(() => ids.value.length === 0);
// 是否显示弹出层
const open = ref(false);
// 是否显示导入弹出层
const importOpen = ref(false);
// 是否显示完成弹出层
const finishOpen = ref(false);
// 弹出层标题
const title = ref("");
// 上传参数
const upload = reactive({
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/qep/inspection/data/importData"
});

// 是否有缺陷数据
const hasDefectData = computed(() => {
  return dataList.value.some(item => item.isQualified === 0 && item.defectName);
});

// 表单参数
const form = reactive({
  id: undefined,
  taskId: undefined,
  paramId: undefined,
  paramName: undefined,
  standardValue: undefined,
  measuredValue: undefined,
  isQualified: 1,
  defectId: undefined,
  responsiblePerson: undefined,
  processResult: undefined,
  remark: undefined
});

// 完成表单参数
const finishForm = reactive({
  id: undefined,
  actualDate: undefined,
  inspectionResult: '合格'
});

// 表单校验
const rules = reactive({
  paramName: [{ required: true, message: "参数名称不能为空", trigger: "blur" }],
  standardValue: [{ required: true, message: "标准值不能为空", trigger: "blur" }],
  measuredValue: [{ required: true, message: "实测值不能为空", trigger: "blur" }],
  isQualified: [{ required: true, message: "是否合格不能为空", trigger: "change" }],
  defectId: [{ required: true, message: "请选择缺陷类型", trigger: "change" }]
});

// 完成表单校验
const finishRules = reactive({
  actualDate: [{ required: true, message: "请选择实际日期", trigger: "blur" }],
  inspectionResult: [{ required: true, message: "请选择检验结论", trigger: "blur" }]
});

// 任务状态工具函数
const getTaskStatusText = (status) => {
  const numStatus = Number(status);
  if (numStatus == 1) return '待检验';
  if (numStatus == 2) return '检验中';
  if (numStatus == 3) return '已完成';
  return '未知(' + status + ')';
};

/** 查询任务详情 */
function getTaskDetail() {
  if (!taskId.value) {
    ElMessage.error('任务ID不存在');
    return;
  }
  console.log('正在获取任务详情，任务ID:', taskId.value);
  taskLoading.value = true;
  getInspectionTask(taskId.value).then(response => {
    console.log('获取任务详情成功:', response.data);
    console.log('任务状态:', response.data.taskStatus);
    // 确保任务状态为数字类型
    if (response.data.taskStatus !== undefined) {
      response.data.taskStatus = Number(response.data.taskStatus);
    }
    taskInfo.value = response.data;
    taskLoading.value = false;
  }).catch(error => {
    console.error('获取任务详情失败:', error);
    taskLoading.value = false;
    ElMessage.error('获取任务详情失败');
  });
}

/** 查询检验数据列表 */
function getDataList() {
  if (!taskId.value) {
    ElMessage.error('任务ID不存在');
    return;
  }
  console.log('正在获取检验数据列表，任务ID:', taskId.value);
  loading.value = true;
  listInspectionDataByTaskId(taskId.value).then(response => {
    console.log('获取检验数据列表成功:', response);
    // 处理可能的不同响应结构
    if (Array.isArray(response)) {
      dataList.value = response;
    } else if (response.data && Array.isArray(response.data)) {
      dataList.value = response.data;
    } else if (response.rows && Array.isArray(response.rows)) {
      dataList.value = response.rows;
    } else {
      dataList.value = [];
      console.warn('未能识别的响应数据结构:', response);
    }
    loading.value = false;
  }).catch(error => {
    console.error('获取检验数据列表失败:', error);
    loading.value = false;
    ElMessage.error('获取检验数据列表失败');
  });
}

/** 查询缺陷类型列表 */
function getDefectList() {
  listDefect().then(response => {
    defectOptions.value = response.rows;
  });
}

/** 获取检验参数列表 */
function getParameterList() {
  getParametersByTaskId(taskId.value).then(response => {
    // 确保返回的数据是数组
    let parameters = [];
    if (response && response.data) {
      parameters = response.data;
    } else if (Array.isArray(response)) {
      parameters = response;
    }
    
    // 过滤掉无效数据并确保关键字段存在
    parameterOptions.value = parameters.filter(item => 
      item && item.paramName && item.standardValue
    );
    
    console.log('获取到参数列表:', parameterOptions.value);
  }).catch(error => {
    console.error('获取参数列表失败:', error);
    ElMessage.error('获取检验参数列表失败');
    parameterOptions.value = [];
  });
}

/** 处理参数变更 */
function handleParameterChange(value) {
  if (!value) return;
  
  // 找到选中的参数对象
  const selected = parameterOptions.value.find(item => item.paramName === value);
  if (selected) {
    currentParameter.value = selected;
    // 自动填充参数ID和标准值
    form.paramId = selected.id || '';
    form.standardValue = selected.standardValue || '';
    // 如果已经输入了实测值，自动判断是否合格
    if (form.measuredValue) {
      handleMeasuredValueChange();
    }
  }
}

/** 处理实测值变更 */
function handleMeasuredValueChange() {
  if (!currentParameter.value || !form.measuredValue) {
    return;
  }
  
  // 获取标准值
  const standardValue = currentParameter.value.standardValue || '';
  const measuredValue = form.measuredValue;
  
  if (!standardValue || !measuredValue) {
    form.isQualified = 0;
    handleQualifiedChange(form.isQualified);
    return;
  }
  
  try {
    // 根据不同格式判断是否合格
    if (standardValue.includes("~") || standardValue.includes("-")) {
      // 范围型标准值，如: 10~20 或 10-20
      const range = standardValue.replace("~", "-").split("-");
      if (range.length < 2) {
        form.isQualified = 0;
      } else {
        const min = parseFloat(range[0].trim());
        const max = parseFloat(range[1].trim());
        const value = parseFloat(measuredValue.trim());
        form.isQualified = (!isNaN(min) && !isNaN(max) && !isNaN(value) && 
                           value >= min && value <= max) ? 1 : 0;
      }
    } else if (standardValue.includes("±")) {
      // 偏差型标准值，如: 10±0.5
      const parts = standardValue.split("±");
      if (parts.length < 2) {
        form.isQualified = 0;
      } else {
        const base = parseFloat(parts[0].trim());
        const deviation = parseFloat(parts[1].trim());
        const value = parseFloat(measuredValue.trim());
        form.isQualified = (!isNaN(base) && !isNaN(deviation) && !isNaN(value) && 
                           value >= (base - deviation) && value <= (base + deviation)) ? 1 : 0;
      }
    } else if (standardValue.includes(">")) {
      // 大于型标准值，如: >10
      const limit = parseFloat(standardValue.replace(">", "").trim());
      const value = parseFloat(measuredValue.trim());
      form.isQualified = (!isNaN(limit) && !isNaN(value) && value > limit) ? 1 : 0;
    } else if (standardValue.includes("≥")) {
      // 大于等于型标准值，如: ≥10
      const limit = parseFloat(standardValue.replace("≥", "").trim());
      const value = parseFloat(measuredValue.trim());
      form.isQualified = (!isNaN(limit) && !isNaN(value) && value >= limit) ? 1 : 0;
    } else if (standardValue.includes("<")) {
      // 小于型标准值，如: <10
      const limit = parseFloat(standardValue.replace("<", "").trim());
      const value = parseFloat(measuredValue.trim());
      form.isQualified = (!isNaN(limit) && !isNaN(value) && value < limit) ? 1 : 0;
    } else if (standardValue.includes("≤")) {
      // 小于等于型标准值，如: ≤10
      const limit = parseFloat(standardValue.replace("≤", "").trim());
      const value = parseFloat(measuredValue.trim());
      form.isQualified = (!isNaN(limit) && !isNaN(value) && value <= limit) ? 1 : 0;
    } else {
      // 相等型标准值，直接比较
      const numStandard = parseFloat(standardValue.trim());
      const numMeasured = parseFloat(measuredValue.trim());
      
      if (!isNaN(numStandard) && !isNaN(numMeasured)) {
        form.isQualified = (Math.abs(numStandard - numMeasured) < 0.00001) ? 1 : 0;
      } else {
        // 如果不是数值型，直接比较字符串
        form.isQualified = (standardValue.trim() === measuredValue.trim()) ? 1 : 0;
      }
    }
  } catch (e) {
    console.error('判断是否合格出错:', e);
    // 默认为不合格
    form.isQualified = 0;
  }
  
  // 触发合格状态变更处理
  handleQualifiedChange(form.isQualified);
}

/** 返回按钮操作 */
function goBack() {
  router.go(-1);
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
}

/** 合格状态变更操作 */
function handleQualifiedChange(value) {
  if (value === 1) {
    form.defectId = undefined;
    form.responsiblePerson = undefined;
    form.processResult = undefined;
  }
}

/** 新增按钮操作 */
function handleAdd() {
  resetForm();
  form.taskId = taskId.value;
  open.value = true;
  title.value = "添加检验数据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  resetForm();
  const dataId = row.id;
  form.id = dataId;
  Object.assign(form, row);
  open.value = true;
  title.value = "修改检验数据";
}

/** 提交按钮 */
function submitForm() {
  if (form.id !== undefined) {
    updateInspectionData(form).then(response => {
      ElMessage.success("修改成功");
      open.value = false;
      getDataList();
    });
  } else {
    addInspectionData(form).then(response => {
      ElMessage.success("新增成功");
      open.value = false;
      getDataList();
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const dataIds = row.id || ids.value;
  ElMessageBox.confirm(
    '是否确认删除选中的检验数据?',
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(function() {
    return delInspectionData(dataIds);
  }).then(() => {
    getDataList();
    ElMessage.success("删除成功");
  });
}

/** 导入按钮操作 */
function handleImport() {
  importOpen.value = true;
}

/** 下载模板操作 */
function importTemplate() {
  getImportTemplate();
}

/** 文件上传中处理 */
function handleFileUploadProgress() {
  upload.isUploading = true;
}

/** 文件上传成功处理 */
function handleFileSuccess(response) {
  upload.isUploading = false;
  importOpen.value = false;
  getDataList();
  ElMessage.success(response.msg);
}

/** 提交上传文件 */
function submitFileForm() {
  document.querySelector('#uploadRef').submit();
}

/** 完成任务按钮操作 */
function handleFinishTask() {
  resetFinishForm();
  finishForm.id = taskId.value;
  finishOpen.value = true;
}

/** 取消完成按钮 */
function cancelFinish() {
  finishOpen.value = false;
  resetFinishForm();
}

/** 完成表单重置 */
function resetFinishForm() {
  finishForm.id = taskId.value;
  finishForm.actualDate = new Date().toISOString().split('T')[0];
  finishForm.inspectionResult = '合格';
}

/** 提交完成表单 */
function submitFinishForm() {
  finishInspectionTask(finishForm).then(response => {
    ElMessage.success('检验任务完成成功');
    finishOpen.value = false;
    getTaskDetail();
    router.push('/inspection/task');
  });
}

/** 表单重置 */
function resetForm() {
  form.id = undefined;
  form.taskId = taskId.value;
  form.paramId = undefined;
  form.paramName = undefined;
  form.standardValue = undefined;
  form.measuredValue = undefined;
  form.isQualified = 1;
  form.defectId = undefined;
  form.responsiblePerson = undefined;
  form.processResult = undefined;
  form.remark = undefined;
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  resetForm();
}

/** 导出按钮操作 */
function handleExport() {
  const inspectionData = {
    taskId: taskId.value
  };
  
  ElMessage.info('正在导出检验数据，请稍候...');
  exportInspectionData(inspectionData).then(response => {
    const blob = new Blob([response]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    const filename = `检验数据_任务${taskId.value}_${new Date().getTime()}.xlsx`;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  }).catch(error => {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
  });
}

/** 导出选中按钮操作 */
function handleExportSelected() {
  if (ids.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  
  const selectedIds = ids.value.join(',');
  ElMessage.info('正在导出选中的检验数据，请稍候...');
  
  exportSelectedInspectionData({
    ids: selectedIds
  }).then(response => {
    const blob = new Blob([response]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    const filename = `检验数据_选中_${new Date().getTime()}.xlsx`;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  }).catch(error => {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
  });
}

onMounted(() => {
  console.log('任务ID:', taskId.value);
  if (!taskId.value) {
    ElMessage.error('任务ID不存在，请返回任务列表重新选择');
    setTimeout(() => router.push('/inspection/task'), 2000);
    return;
  }
  getTaskDetail();
  getDataList();
  getDefectList();
  getParameterList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.task-header h3 {
  margin: 0;
}

.status-tag {
  margin-left: 10px;
}

.detail-form {
  padding: 10px 20px;
}
</style> 